#include "DownloadManager.hpp"

namespace Eyer {
    DownloadManager * DownloadManager::instance = nullptr;
    std::mutex DownloadManager::instanceMut;
    DownloadManager * DownloadManager::GetInstance()
    {
        // TODO Locker
        std::unique_lock<std::mutex> lock(instanceMut);
        if(instance == nullptr){
            instance = new DownloadManager();
        }
        return instance;
    }


    DownloadManager::DownloadManager() 
    {

    }

    DownloadManager::~DownloadManager() 
    {

    }

    std::shared_ptr<Downloader> DownloadManager::GetDownloader(const std::string &path) 
    {
        std::unique_lock<std::mutex> lock(downloaderMut);

        if(downloaderVec.size() > 500){
            for(int i=0; i<downloaderVec.size(); i++){
                //printf("====before downloadManager[%d]:%ld ,vecSize:%d, path:%s\n", i, downloaderVec[i].use_count(), downloaderVec.size(), downloaderVec[i]->path.c_str());
                if(downloaderVec[i].use_count() <= 1){
                    downloaderVec.erase(downloaderVec.begin() + i);
                }
                if(downloaderVec.size() <= 500){
                    break;
                }
            }
        }

        for(int i=0; i<downloaderVec.size(); i++){
            if(downloaderVec[i]->path == path){
                return downloaderVec[i];
            }
        }

        std::shared_ptr<Downloader> downloader = std::make_shared<Downloader>(path);
        downloaderVec.push_back(downloader);
        return downloader;
    }
}